package org.hako.recite.word.tool;

import java.util.ArrayList;
import java.util.List;

/**
 * Detect double kannji in two chars.
 * 
 * @since 0.4.14
 * @author <a href="mailto:xnnyygn@gmail.com">xnnyygn</a>
 */
public class SameCharsKannjiDetector implements KannjiYomiDetector {

	@Override
	public boolean check(String rawKannji, String rawYomi,
			KannjiExtractResult extractResult) {
		return rawKannji.length() == rawYomi.length();
	}

	@Override
	public KannjiYomiDetectResult detect(String rawKannji, String rawYomi,
			KannjiExtractResult extractResult) {
		int kannjiCount = extractResult.getCount();
		List<KannjiYomiPair> pairs = new ArrayList<KannjiYomiPair>(kannjiCount);
		for (int i = 0; i < kannjiCount; i++) {
			int index = extractResult.get(i);
			pairs.add(new KannjiYomiPair(rawKannji.substring(index, index + 1),
					rawYomi.substring(index, index + 1)));
		}
		return new KannjiYomiDetectResult(pairs, generateKannjiWithYomi(
				rawKannji, rawYomi));
	}

	/**
	 * Generate kannji with yomi.
	 * 
	 * @param rawKannji
	 * @param rawYomi
	 * @return
	 */
	private String generateKannjiWithYomi(String rawKannji, String rawYomi) {
		StringBuilder builder = new StringBuilder();
		int length = rawKannji.length();
		for (int i = 0; i < length; i++) {
			char ck = rawKannji.charAt(i);
			char cy = rawYomi.charAt(i);
			if (ck == cy) {
				builder.append(ck);
			} else {
				builder.append(ck);
				builder.append('(');
				builder.append(cy);
				builder.append(')');
			}
		}
		return builder.toString();
	}
}
